package com.ruoyi.media.orderManage.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.helper.LoginHelper;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.core.domain.PageQuery;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ruoyi.media.pay.entity.PayEntity;
import com.ruoyi.media.utils.WxUtils;
import com.ruoyi.media.vipProduct.domain.MediaVipProduct;
import com.ruoyi.media.vipProduct.service.IMediaVipProductService;
import lombok.RequiredArgsConstructor;
import org.apache.bcel.generic.NEW;
import org.springframework.stereotype.Service;
import com.ruoyi.media.orderManage.domain.bo.MediaOrderManageBo;
import com.ruoyi.media.orderManage.domain.vo.MediaOrderManageVo;
import com.ruoyi.media.orderManage.domain.MediaOrderManage;
import com.ruoyi.media.orderManage.mapper.MediaOrderManageMapper;
import com.ruoyi.media.orderManage.service.IMediaOrderManageService;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
import java.util.Collection;

/**
 * 软件支付订单管理Service业务层处理
 *
 * @author dqw
 * @date 2023-05-24
 */
@RequiredArgsConstructor
@Service
public class MediaOrderManageServiceImpl extends ServiceImpl<MediaOrderManageMapper,MediaOrderManage> implements IMediaOrderManageService {

    private final MediaOrderManageMapper baseMapper;

//    private final ISysUserService userService;

    /**
     * 会员套餐对象
     */
    private final IMediaVipProductService mediaVipProductService;

    /**
     * 查询软件支付订单管理
     */
    @Override
    public MediaOrderManageVo queryById(Long id){
        return baseMapper.selectVoById(id);
    }

    /**
     * 查询软件支付订单管理列表
     */
    @Override
    public TableDataInfo<MediaOrderManageVo> queryPageList(MediaOrderManageBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<MediaOrderManage> lqw = buildQueryWrapper(bo);
        Page<MediaOrderManageVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询软件支付订单管理列表
     */
    @Override
    public List<MediaOrderManageVo> queryList(MediaOrderManageBo bo) {
        LambdaQueryWrapper<MediaOrderManage> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<MediaOrderManage> buildQueryWrapper(MediaOrderManageBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<MediaOrderManage> lqw = Wrappers.lambdaQuery();
        lqw.eq(bo.getDeptId() != null, MediaOrderManage::getDeptId, bo.getDeptId());
        lqw.eq(bo.getUserId() != null, MediaOrderManage::getUserId, bo.getUserId());
        lqw.eq(StringUtils.isNotBlank(bo.getVipType()), MediaOrderManage::getVipType, bo.getVipType());
        lqw.eq(StringUtils.isNotBlank(bo.getDescription()), MediaOrderManage::getDescription, bo.getDescription());
        lqw.eq(StringUtils.isNotBlank(bo.getPrice()), MediaOrderManage::getPrice, bo.getPrice());
        lqw.eq(bo.getOpeningTime() != null,MediaOrderManage::getOpeningTime, bo.getOpeningTime());
        lqw.eq(StringUtils.isNotBlank(bo.getTimeType()), MediaOrderManage::getTimeType, bo.getTimeType());
        return lqw;
    }

    /**
     * 新增软件支付订单管理
     */
    @Override
    public Boolean insertByBo(MediaOrderManageBo bo) {
        MediaOrderManage add = BeanUtil.toBean(bo, MediaOrderManage.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 修改软件支付订单管理
     */
    @Override
    public Boolean updateByBo(MediaOrderManageBo bo) {
        MediaOrderManage update = BeanUtil.toBean(bo, MediaOrderManage.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(MediaOrderManage entity){
        //TODO 做一些数据校验,如唯一约束
        LoginUser loginUser =  LoginHelper.getLoginUser();
        entity.setNickname(loginUser.getUsername());
        entity.setUserId(loginUser.getUserId());
        entity.setDeptId(loginUser.getDeptId());
    }

    /**
     * 批量删除软件支付订单管理
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }


    /**
     * 创建订单
     * @param payEntity
     * @return
     */
    @Override
    public MediaOrderManage createOrder(PayEntity payEntity) {
        MediaOrderManage mediaOrderManage = new MediaOrderManage();
        //开通时长
        mediaOrderManage.setOpeningTime(payEntity.getDuration());

        //会员类型
        mediaOrderManage.setTimeType(payEntity.getVersion());
        mediaOrderManage.setVipType(payEntity.getVersion());

        //获取会员套餐对象
        LambdaQueryWrapper<MediaVipProduct> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(MediaVipProduct::getVipType,payEntity.getVersion());
        MediaVipProduct mediaVipProducts = mediaVipProductService.getOne(queryWrapper);

        //当前套餐价格BigDecimal
        BigDecimal priceBig = new BigDecimal(mediaVipProducts.getPrice());

        //计算套餐价格   月卡
        if(payEntity.getTimeType().equals("month")){
            mediaOrderManage.setPrice(priceBig.multiply(new BigDecimal(payEntity.getDuration())).toString());
        //年卡
        }else{
            mediaOrderManage.setPrice(priceBig.multiply(new BigDecimal("12").multiply(new BigDecimal(payEntity.getDuration()))).toString());
        }
        mediaOrderManage.setDescription(mediaVipProducts.getName());

        //创建订单编号
        String orderId = mediaVipProducts.getCode() + DateUtils.dateTimeNow() + WxUtils.getRandomNumber(6);
        mediaOrderManage.setOrderId(orderId);
        mediaOrderManage.setId(orderId);

        //校验参数
        validEntityBeforeSave(mediaOrderManage);
         //保存订单数据
        save(mediaOrderManage);
        return mediaOrderManage;
    }


    /**
     * 修改订单状态 并处理订单支付后逻辑
     * @param id
     * @param status
     * @return
     */
    @Override
    public boolean updateOrderStatus(String id, int status) {
        //获取订单数据
        MediaOrderManage mediaOrderManage =  getById(id);
        //获取当前用户对象
//        SysUser sysUser =  userService.selectUserById(mediaOrderManage.getUserId());

        Long[] roleId = {};
        if(mediaOrderManage.getVipType().equals("1")){
            roleId = new Long[]{Long.parseLong("1658719994530025474")};  //添加标准版权限
        }else if(mediaOrderManage.getVipType().equals("2")){
            roleId = new Long[]{Long.parseLong("1661252150380843010")};  //添加高级版权限
        }else if(mediaOrderManage.getVipType().equals("3")){
            roleId = new Long[]{Long.parseLong("1661252769388810241")};  //添加旗舰版权限
        }

//        sysUser.setRoleIds(roleId);
//        userService.insertUserAuth(sysUser.getUserId(), roleId);
        mediaOrderManage.setStatus(status);
        return updateById(mediaOrderManage);
    }


}
